package com.wlgzs.booksystem.config;
import com.wlgzs.booksystem.config.jwt.JWTFilter;
import org.apache.log4j.Logger;
import org.apache.shiro.mgt.DefaultSessionStorageEvaluator;
import org.apache.shiro.mgt.DefaultSubjectDAO;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import sun.rmi.runtime.Log;

import javax.servlet.Filter;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author wlgzs-sjl
 * @date 2020/11/12 20:38
 */
@Configuration
public class ShiroConfig {

    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("getDefaultWebSecurityManager") DefaultWebSecurityManager defaultWebSecurityManager){
        ShiroFilterFactoryBean bean=new ShiroFilterFactoryBean();

        // 添加自己的过滤器并且取名为jwt
        Map<String,Filter> filterMap=new LinkedHashMap<>();
        //设置我们自定义的JWT过滤器
        filterMap.put("jwt",new JWTFilter());
        bean.setFilters(filterMap);

        bean.setSecurityManager(defaultWebSecurityManager);
        //设置安全管理器
        Map<String,String> filterRuleMap=new LinkedHashMap<>();

        //所有请求通过我们自己的JWT Filter
        //filterRuleMap.put("/back/**","roles[user:admin]");
        System.out.println("所有请求进入我们自己的JWT Filter");
        filterRuleMap.put("/**","jwt");

        //放行Swagger接口
        filterRuleMap.put("/swagger-ui.html","anon");
        filterRuleMap.put("/login/**","anon");

        bean.setFilterChainDefinitionMap(filterRuleMap);

        //设置登录的请求
        bean.setLoginUrl("/login/toLogin");
        //未授权页面
        bean.setUnauthorizedUrl("/login/toLogin");
        return bean;
    }

    @Bean
    public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm){
        DefaultWebSecurityManager securityManager=new DefaultWebSecurityManager();
        securityManager.setRealm(userRealm);

        /*
         * 关闭shiro自带的session，详情见文档
         * http://shiro.apache.org/session-management.html#SessionManagement-StatelessApplications%28Sessionless%29
         */
        DefaultSubjectDAO subjectDAO = new DefaultSubjectDAO();
        DefaultSessionStorageEvaluator defaultSessionStorageEvaluator = new DefaultSessionStorageEvaluator();
        defaultSessionStorageEvaluator.setSessionStorageEnabled(false);
        subjectDAO.setSessionStorageEvaluator(defaultSessionStorageEvaluator);
        securityManager.setSubjectDAO(subjectDAO);
        return securityManager;
    }

    @Bean
    public UserRealm userRealm(){
        return new UserRealm();
    }

}
